<template>
  <div style="overflow: hidden; height: 100vh; width: 100%; display: flex; flex-direction: column;">
    <!-- 搜索表单，固定顶部 -->
    <el-form :inline="true" style="display: flex; align-items: center; flex-wrap: wrap; width: 100%;" border>
      <el-form-item label=" 商品名称" style="margin-right: 10px; flex: 1;">
        <el-input v-model="ABC.goods_Name" placeholder="请输入商品名称" />
      </el-form-item>

      <el-form-item label="商品规格" style="margin-right: 10px; flex: 1;">
        <el-input v-model="ABC.goods_Spec" placeholder="请输入商品规格" />
      </el-form-item>

      <el-form-item label="商品编码" style="margin-right: 10px; flex: 1;">
        <el-input v-model="ABC.goods_Code" placeholder="请输入商品编码" />
      </el-form-item>

      <el-form-item label="商品品牌" style="margin-right: 10px; flex: 1;">
        <el-input v-model="ABC.goods_Brand" placeholder="请输入商品品牌" />
      </el-form-item>

      <el-form-item label="商品类别" style="margin-right: 10px; flex: 1;">
        <el-input v-model="ABC.goods_Category" placeholder="请输入商品类别" />
      </el-form-item>

      <el-button type="success" @click="GoodsInfoQuery">查询</el-button>
      <el-button type="primary" @click="dialog = true">新增</el-button>
    </el-form>

    <!-- 表格部分，允许滚动 -->
    <div style="flex: 1; overflow: auto;">
      <el-table :data="tableData" style="min-width: 1500px;">
        <el-table-column prop="goods_Id" label="编号"></el-table-column>
        <el-table-column prop="vendor_Name" label="商品供应商"></el-table-column>
        <el-table-column prop="goods_Name" label="商品名称"></el-table-column>
        <el-table-column prop="goods_Grade" label="商品等级"></el-table-column>
        <el-table-column prop="goods_Code" label="商品编码"></el-table-column>
        <el-table-column prop="goods_BarCode" label="商品条码"></el-table-column>
        <el-table-column prop="goods_Spec" label="商品规格" ></el-table-column>
        <el-table-column prop="goods_Category" label="商品类别"></el-table-column>
        <el-table-column prop="goods_Brand" label="商品品牌"></el-table-column>
        <el-table-column prop="goods_Origin" label="商品产地"></el-table-column>
        <el-table-column prop="goods_ShelfMonth" label="商品保质期"></el-table-column>
        <el-table-column prop="goods_SellingPrice" label="商品售价"></el-table-column>
        <el-table-column prop="goods_Status" label="商品状态">
          <template v-slot="scope">{{ getStatusText(scope.row.goods_Status) }}</template>
        </el-table-column>
        <el-table-column prop="goods_Remark" label="备注"></el-table-column>
        <el-table-column label="操作" width="250" fixed="left">
          <template v-slot="scope">
            <div style="display: flex; justify-content: space-around;">
              <el-button type="danger" @click="handleDelete(scope.row.goods_Id)">删除</el-button>
              <el-button type="success" @click="handleStorageClick(scope.row.goods_Id, true)">入库</el-button>
              <el-button style="background-color: aquamarine;"
                @click="handleSpecsClick(scope.row.goods_Spec, scope.row.goods_Id, true)">规格</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页部分，避免遮挡 -->
    <div style="position: relative; margin-top: 12px;">
      <el-pagination v-model:current-page="ABC.pageIndex" v-model:page-size="ABC.pageSize" :page-sizes="[1, 5, 10, 30]"
        background layout="total, sizes, prev, pager, next, jumper" :total="ABC.totalCount"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </div>
  <!--规格弹窗-->
  <el-dialog v-model="logic.specsOpen" title="商品规格" width="500">
    <el-form :model="specs_data">
      <el-form-item label="长" :label-width="formLabelWidth">
        <el-input v-model="specs_data.specifications_Length" autocomplete="off" />
      </el-form-item>
      <el-form-item label="宽" :label-width="formLabelWidth">
        <el-input v-model="specs_data.specifications_Width" autocomplete="off" />
      </el-form-item>
      <el-form-item label="高" :label-width="formLabelWidth">
        <el-input v-model="specs_data.specifications_Height" autocomplete="off" @change="ChangeWV" />
      </el-form-item>
      <el-form-item label="体积" :label-width="formLabelWidth">
        <el-input :disabled="true" v-model="specs_data.specifications_Volume" autocomplete="off" />
      </el-form-item>
      <el-form-item label="重量" :label-width="formLabelWidth">
        <el-input :disabled="true" v-model="specs_data.specifications_Weight" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="logic.specsOpen = false">取消</el-button>
        <el-button type="primary" @click="specsAdd">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--入库弹窗-->
  <el-dialog v-model="logic.storageOpne" title="入库信息" width="500">
    <el-form :model="storageData">
      <el-form-item label="仓库" :label-width="formLabelWidth">
        <el-select v-model="logic.showWarehouseAreaId" placeholder="选择仓库" @change="showReservoir">
          <!--@vue-ignore-->
          <el-option v-for="item in showWarehouseArea" :key="item.warehouse_AreaCode" :label="item.warehouse_AreaName"
            :value="item.warehouse_AreaCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="库区" :label-width="formLabelWidth">
        <el-select v-model="logic.showReservoirAreaId" placeholder="选择库区" @change="showBin">
          <!--@vue-ignore-->
          <el-option v-for="item in showReservoirArea" :key="item.reservoir_AreaId" :label="item.reservoir_AreaName"
            :value="item.reservoir_AreaId" />
        </el-select> 
      </el-form-item>
      <el-form-item label="库位" :label-width="formLabelWidth">
        <el-select v-model="storageData.goodsInWL_BinLocationId" placeholder="选择库位">
          <!--@vue-ignore-->
          <el-option v-for="item in showBinLocation" :key="item.binL_Id" :label="item.binL_Code"
            :value="item.binL_Id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="logic.storageOpne = false">取消</el-button>
        <el-button type="primary" @click="addStorage">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import axios from 'axios';
import { ref, onMounted, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router';
import axiosHelper from '@/components/AxiosRequest/axiosHelper';

//获取仓库下拉框
const showWarehouseArea = ref([])
function showWarehouse() {
  axiosHelper.readAxios("api/BinLocation/QueryWareHouse", {
    method: 'get'
  })
    .then(res => {
      showWarehouseArea.value = res.data.data
    })
}
//获取库区下拉框
const showReservoirArea = ref([])
function showReservoir() {
  //console.log(logic.showWarehouseAreaId)
  axiosHelper.readAxios("api/BinLocation/QueryReservoirArea",
    {
      method: "get",
      params: {
        warehouse_AreaCode: logic.showWarehouseAreaId
      }
    }
  )
    .then(res => {
      showReservoirArea.value = res.data.data

    })
}
//获取库位下拉框
const showBinLocation = ref([])
function showBin() {
  console.log(logic.showReservoirAreaId)
  axiosHelper.readAxios("api/BinLocation/QueryBinL", {
    method: "get",
    params: {
      reservoir_AreaId: logic.showReservoirAreaId
    }
  })
    .then(res => {
      //console.log(res)
      showBinLocation.value = res.data.data
    })
}

//创建逻辑对象
const logic = reactive({
  specsOpen: false,//规格弹窗
  specsId: "",//规格弹窗id
  goodsId: "",
  storageOpne: false,//入库弹窗
  storageGoodsId: "",
  showWarehouseAreaId: "",//入库弹窗仓库id
  showReservoirAreaId: "",//入库弹窗库区id
})

// 添加事件监听逻辑，当值更改时自动清空依赖字段
watch(() => logic.showWarehouseAreaId, (newVal) => {
  if (newVal) {
    logic.showReservoirAreaId = "";           // 更改仓库后清空库区
    storageData.goodsInWL_BinLocationId = ""; // 清空库位
    showReservoir();                          // 更新库区列表
  }
});

watch(() => logic.showReservoirAreaId, (newVal) => {
  if (newVal) {
    storageData.goodsInWL_BinLocationId = ""; // 更改库区后清空库位
    showBin();                                // 更新库位列表
  }
});

//入库点击按钮
const handleStorageClick = (goodsId: string, isOpen: boolean) => {
  if (isOpen) {
    //初始化入库弹窗数据
    storageData.goodsInWL_BinLocationId = "";
    logic.showWarehouseAreaId = "";
    logic.showReservoirAreaId = "";
    showWarehouseArea.value = []
    showReservoirArea.value = []
    showBinLocation.value = []
  }

  logic.storageOpne = isOpen
  logic.storageGoodsId = goodsId
  showWarehouse()
}
//入库表单对象 
const storageData = reactive(
  {
    goodsInWL_Id: "",
    goodsInWL_GoodsId: "",
    goodsInWL_BinLocationId: ""
  }
)
//入库方法
function addStorage() {
  storageData.goodsInWL_GoodsId = logic.storageGoodsId
  //console.log(storageData)
  axiosHelper.writeAxios("api/Storage/InsertStorageAsync", {
    method: 'post',
    data: storageData
  })
    .then(res => {
      console.log(res);
      if (res.data.code == 200) {
        ElMessage.success("入库成功");
        logic.storageOpne = false;
        GoodsInfoQuery();
      }
      else {
        ElMessage.error(res.data.message);
        //return;
      }
    })
}

//规格列表
const specifications = ref<any>([])
function showSpecs() {
  axiosHelper.readAxios("/api/GoodsInfo/QuerySpecsById", {
    method: "get",
    params: {
      specifications_Id: logic.specsId
    }
  })
    .then(res => {
      specifications.value = res.data.data
      //console.log(specifications.value)
      specs_data.specifications_Height = specifications.value.specifications_Height
      specs_data.specifications_Length = specifications.value.specifications_Length
      specs_data.specifications_Width = specifications.value.specifications_Width
      specs_data.specifications_Volume = specifications.value.specifications_Volume
      specs_data.specifications_Weight = specifications.value.specifications_Weight


    })
}
//规格按钮
const handleSpecsClick = (specsId: string, goodsId: string, isOpen: boolean) => {
  logic.specsOpen = isOpen
  logic.specsId = specsId
  logic.goodsId = goodsId

  //获取规格
  showSpecs();
  //清空元素
  specs_data.specifications_Height = ""
  specs_data.specifications_Length = ""
  specs_data.specifications_Width = ""
  specs_data.specifications_Volume = ""
  specs_data.specifications_Weight = ""
}

// 定义商品状态枚举
const enumGoodsStatus = reactive([
  { value: 0, label: '待处理' },
  { value: 1, label: '待入库' },
  { value: 2, label: '已入库' },
  { value: 3, label: '待出库' },
  { value: 4, label: '已出库' },
]);
//状态
const getStatusText = (status: number): string => {
  switch (status) {
    case 0:
      return '待处理';
    case 1:
      return '待入库';
    case 2:
      return '已入库';
    case 3:
      return '待出库';
    default:
      return '已出库';
  }
}
const grade = ref(['A类', 'B类', 'C类']);
const categories = ref(['类别A', '类别B', '类别C', '类别D', '类别E', '类别F']);
const brands = ref(['品牌A', '品牌B', '品牌C', '品牌D', '品牌E', '品牌F']);

const router = useRouter();
// 商品信息添加
const formLabelWidth = '80px'
// const dialogFormVisible = ref(false)
// let timer

const dialog = ref(false)

const form = reactive({
  goods_VendorId: "",
  goods_Name: "",
  goods_Grade: "",
  goods_Code: "",
  goods_BarCode: "123",
  goods_Spec: "",
  goods_Category: "",
  goods_Brand: "",
  goods_Origin: "",
  goods_ContactPerson: "",
  goods_ContactPhone: "",
  goods_ShelfMonth: "",
  goods_SellingPrice: "",
  goods_Unit: "",
  goods_WeightUnit: "",
  goods_Remark: "",
})

const addTraceability = () => {
  axios.post('http://localhost:5259/api/GoodsCreate/CreateGoods', form)
    .then(response => {
      if (response.data.code === 200) {
        ElMessage.success('添加成功');
        dialog.value = false;
        refreshTableData();
      } else {
        ElMessage.error(response.data.message);
      }
    })
    .catch(error => {
      const errorMessage = error.response?.data?.message || '请求失败，请稍后再试';
      ElMessage.error(errorMessage);
    });
}

const refreshTableData = () => {
  GoodsInfoQuery()
}

//显示
const tableData = ref([])
const ABC = reactive({
  goods_Name: '',
  goods_Spec: '',
  goods_Code: '',
  goods_BarCode: '',
  goods_Brand: '',
  goods_Category: '',
  totalCount: 0,
  totalPage: 0,
  pageIndex: 1,
  pageSize: 10,
})
//显示
const GoodsInfoQuery = () => {
  axios.get('http://localhost:5115/api/GoodsInfo/GetGoodsInfo', {
    params: {
      goods_Name: ABC.goods_Name,
      goods_Spec: ABC.goods_Spec,
      goods_Code: ABC.goods_Code,
      goods_BarCode: ABC.goods_BarCode,
      goods_Brand: ABC.goods_Brand,
      goods_Category: ABC.goods_Category,
      pageIndex: ABC.pageIndex,
      pageSize: ABC.pageSize,
    }
  }).then(res => {
    tableData.value = res.data.data.data
    //console.log(res)
    ABC.totalCount = res.data.data.totalCount
    ABC.totalPage = res.data.data.totalPage
  })
}

//创建规格表单对象
const specs_data = reactive({
  goodsDto_Id: "",
  specifications_Id: "",
  specifications_Width: "",
  specifications_Height: "",
  specifications_Length: "",
  specifications_Volume: "",
  specifications_Weight: ""
})
//动态重量及体积
function ChangeWV() {
  specs_data.specifications_Volume = (Number(specs_data.specifications_Width) * Number(specs_data.specifications_Height) * Number(specs_data.specifications_Length)).toFixed(2)
  specs_data.specifications_Weight = (Number(specs_data.specifications_Volume) * 0.001).toFixed(2)
}
//新增规格
function specsAdd() {
  specs_data.specifications_Id = logic.specsId
  specs_data.goodsDto_Id = logic.goodsId
  //校验
  if (specs_data.specifications_Width.length == 0) {
    ElMessage.error("请输入规格宽度");
    return;
  }
  if (specs_data.specifications_Height.length == 0) {
    ElMessage.error("请输入规格高度");
    return;
  }
  if (specs_data.specifications_Length.length == 0) {
    ElMessage.error("请输入规格长度");
    return;
  }

  axiosHelper.writeAxios("api/GoodsCreate/CreateSpecs", {
    method: 'post',
    data: specs_data
  })
    .then(res => {
      console.log(res);
      if (res.data.code == 200) {

        ElMessage.success("新增成功");
        GoodsInfoQuery();
        logic.specsOpen = false;
      }
      else {
        ElMessage.error(res.data.message);
        return;
      }
    })
}

//删除
const handleDelete = (row:any) => {
  ElMessageBox.confirm(
    '确定删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    axios.delete("http://localhost:5259/api/GoodsCreate/DeleteGoods?goods_Id=" + row.goods_Id).then(res => {
      if (res.data.code == 200) {
        ElMessage.success("删除成功")
        GoodsInfoQuery()
      }
      else {
        ElMessage.error(res.data.message)
      }
    })
  })

    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}
onMounted(() => {
  GoodsInfoQuery()
})
const handleSizeChange = (val: number) => {
  ABC.pageSize = val
  GoodsInfoQuery()

}
const handleCurrentChange = (val: number) => {
  ABC.pageIndex = val
  GoodsInfoQuery()
}

//编辑
function handleEdit() {

}
</script>

<style>
.input-with-select {
  margin-bottom: 20px;
}
</style>